package com.malamute.core.listener;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

import com.malamute.system.entity.TreeNode;
import com.malamute.system.entity.User;

/**
 * 初始化监听
 * 
 */
public class InitDataListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {

	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		Properties props = new Properties();
		InputStream in = null;
		try {
			ClassLoader cl = this.getClass().getClassLoader();
			in = cl.getResourceAsStream("jdbc.properties");
			// InputStream in = new BufferedInputStream(new FileInputStream(
			// "jdbc.properties"));
			props.load(in);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Configuration cfg = new AnnotationConfiguration().configure();
		cfg.setProperties(props);
		// cfg.addClass(User.class);
		SessionFactory sessionFactory = cfg.buildSessionFactory();
		Session session = sessionFactory.openSession();
		saveAdmin(session);
		saveTreeNode(session);
		session.close();
		props.clear();
	}

	private void saveAdmin(Session session) {
		List list = session
				.createQuery(" from User u where u.username='admin'").list();
		if (list.isEmpty()) {
			Transaction tx = session.beginTransaction();
			User admin = new User();
			admin.setName("管理员");
			admin.setUsername("admin");
			admin.setPassword("admin");
			admin.setCreateTime(new Date());
			admin.setAdmin(true);
			admin.setCreator("System");
			session.save(admin);
			tx.commit();
		}
	}

	private void saveTreeNode(Session session) {
		List list = session.createQuery(" from TreeNode t where t.text='ROOT'")
				.list();
		if (list.isEmpty()) {
			Transaction tx = session.beginTransaction();
			TreeNode rootNode = new TreeNode();
			rootNode.setLeaf(false);
			rootNode.setText("ROOT");
			session.save(rootNode);
			tx.commit();
		}
	}

	public static void main(String[] args) {
		InitDataListener i = new InitDataListener();
		i.contextInitialized(null);
	}

}
